import type {TaskList} from "./type";
import {TaskStartResult} from "./type";

class AsyncController {
    private readonly taskList: TaskList;
    private readonly maxNum: number;

    constructor(taskList: TaskList, maxNum = 10) {
        this.taskList = taskList;
        this.maxNum = maxNum;
    }

    public startTask(): TaskStartResult {
        return new Promise((resolve) => {
            if (this.taskList.length === 0) {
                // 当前任务数量为0 直接resolve
                resolve([]);
                return;
            }
            // 保存任务执行结果
            const results: any[] = [];
            let index = 0; // 下一个任务的下标
            let count = 0; // 当前任务完成的数量
            const taskList = this.taskList;


            // 执行单个任务
            async function doTask() {
                if (index === taskList.length) return;
                const i = index; // 保存序号，使result和items相对应
                const currentTask = taskList[index];
                index++;
                try {
                    results[i] = await currentTask();
                } catch (err) {
                    results[i] = err;
                } finally {
                    count++;
                    // 判断是否所有的任务都已完成
                    if (count === taskList.length) {
                        resolve(results);
                    }
                   doTask();
                }
            }

            // maxRequestNum和taskList.length取最小进行调用
            const times = Math.min(this.maxNum, this.taskList.length);
            for (let i = 0; i < times; i++) {
                doTask();
            }
        })
    }
}


export {
    AsyncController
} ;